<?php

class reservation_model extends MY_Model 
{
	public function __construct() 
	{
		parent::__construct();
	}
	
	public function getReservationArray( $idOsoba, $date, & $courtReservationArray, & $fromTime, & $toTime )
	{
		$courtReservationArray = array();
		$dayInWeek = date( "w", strtotime($date));
		$dayType = 0;
		if ($dayInWeek == 0 || $dayInWeek == 6)
			$dayType = 1;
		
		try
		{
			$instance = DbPdo::getInstance();
			$statement = $instance->prepare( "SELECT fromtimenumber, totimenumber FROM openhours WHERE daydate = :daydate");
			$statement->bindParam( ":daydate", $date, PDO::PARAM_STR );
			$statement->execute();
			$result = $statement->fetch( PDO::FETCH_NUM );
			if (! $result)
			{
				$statement = $instance->prepare( "SELECT fromtimenumber, totimenumber FROM openhours WHERE daytype = :daytype AND daydate IS NULL");
				$statement->bindParam( ":daytype", $dayType, PDO::PARAM_INT );
				$statement->execute();
				$result = $statement->fetch( PDO::FETCH_NUM );
				if (! $result)
				{
					$this->setErrorString( __FUNCTION__ . ": Unable to fetch from openhours" );
					return false;
				}
			}

			$fromTime = $result[0];
			$toTime = $result[1];
			
			for ($i = 0; $i < 5; $i ++)
			{
				$courtReservation = new stdClass();
				$courtReservation->courtNumber = $i;
				$courtReservation->courtType = ($i < 3) ? CourtType::WholeHourCourt : CourtType::HalfHourCourt;
				$courtReservation->reserved = array();
				for ($j = 0; $j < 24; $j ++)
				{
					$courtReservation->reserved[$j] = new stdClass();
					$courtReservation->reserved[$j]->customerId = -1;
					if ($j < $fromTime || $j > $toTime)
						$courtReservation->reserved[$j]->reservationType = ReservationType::NotPossibleReserve;
					else
						$courtReservation->reserved[$j]->reservationType = ReservationType::Free;
				}
				
				array_push($courtReservationArray, $courtReservation);
			}
			
			$instance = DbPdo::getInstance();
			$statement = $instance->prepare( "SELECT customerid, courtnumber, timenumber, reservationtype FROM reservations WHERE reservationdate = :reservationdate");
			$statement->bindParam( ":reservationdate", $date, PDO::PARAM_STR );
			$statement->execute();
			while ($row = $statement->fetch(PDO::FETCH_OBJ))
			{
				$reservedItem = &$courtReservationArray[$row->courtnumber]->reserved[$row->timenumber];
				$reservedItem->reservationType = $row->reservationtype;
				$reservedItem->customerId = $row->customerid;
			}
			
		}
		catch(PDOException $e)
		{
			$this->setErrorString(  __FUNCTION__ . ": " . $e->getMessage() );
			return false;
		}

		return true;
	}
}

?>
